from frameworks.utils.FetchHttp import *
import pandas as pd
from math import *
import re
import datetime
import requests
import httpx
import httpcore
import urllib3
import time
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class StockBaseInfo:
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'close',
        'Cookie': 'timezoneOffset=28800,0; _ga=GA1.2.2068924460.1568258364; browserid=1637567403399993326; '
                  'sessionid=0be65a169d686e464855602e; _gid=GA1.2.614169347.1590475272; '
                  'steamMachineAuth76561199007171441=CA87107A153BDC24FE6D54504A124395F9C36243; '
                  'deep_dive_carousel_focused_app=673750; deep_dive_carousel_method=gems; '
                  'steamCountry=HK%7C413cfd508f5a328ba1679f9252231a8e; '
                  'app_impressions=377530@1_7_7_topsellers_150_3|1245200@1_7_7_topsellers_150_3|632360'
                  '@1_7_7_topsellers_150_3|1245180@1_7_7_topsellers_150_3|1298590@1_7_7_topsellers_150_3|285900'
                  '@1_7_7_topsellers_150_3|632470@1_7_7_topsellers_150_2|813780@1_7_7_topsellers_150_2|1100600'
                  '@1_7_7_topsellers_150_2|1293820@1_7_7_topsellers_150_2|952860@1_7_7_topsellers_150_2|1209110'
                  '@1_7_7_topsellers_150_2|1015610@1_7_7_topsellers_150_3|1238440@1_7_7_topsellers_150_3|1042550'
                  '@1_7_7_topsellers_150_3|466560@1_7_7_topsellers_150_3|602960@1_7_7_topsellers_150_3|457140'
                  '@1_7_7_topsellers_150_3|793460@1_7_7_topsellers_150_3|512540@1_7_7_topsellers_150_3|619150'
                  '@1_7_7_topsellers_150_3|1100410@1_7_7_topsellers_150_3|1088780@1_7_7_topsellers_150_3|1100420'
                  '@1_7_7_topsellers_150_3|1201360@1_7_7_topsellers_150_3|642280@1_7_7_topsellers_150_3|673950'
                  '@1_7_7_topsellers_150_3|613830@1_7_7_topsellers_150_3|636480@1_7_7_topsellers_150_3|387990'
                  '@1_7_7_topsellers_150_3|414700@1_7_7_topsellers_150_3|382310@1_7_7_topsellers_150_3|1162520'
                  '@1_7_7_topsellers_150_2|289070@1_7_7_topsellers_150_2|307690@1_7_7_topsellers_150_2|973760'
                  '@1_7_7_topsellers_150_2|1273370@1_5_9__405; recentapps=%7B%22578080%22%3A1590476900%7D',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20210911 Firefox/52.0'
    }

    def __init__(self):
        pass

    def get_mpfData(self,code,n=5):
        data = self.getSinaStockMiniteInfo(self.translateSinaCode(code),n)
        print(data)
        df1 = pd.read_json(data)
        df1["day"] = pd.to_datetime(df1["day"])
        df2 = df1.rename(columns={'day': 'Datetime', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'volume': 'Volume'})
        df3 = df2.set_index(['Datetime'])
        df3['Adj Close'] = pd.Series(df3["Close"], index=df3.index)
        return df3

    def getSinaStockInfo(self,code):
        code = code.replace(".", "")
        fetch_http = FetchHttp()
        contents = fetch_http.fetch("http://hq.sinajs.cn/list=" + code,"gbk")
        data = contents[13:-3].replace('="', ',').split(',')  # 删除、替换无关字符
        return data

    def getSinaStockMiniteInfo(self,code,n=5):
        fetch_http = FetchHttp()
        contents = fetch_http.fetch("http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=" + code + "&scale=" + str(n) + "&ma=no&datalen=100","gbk")
        return contents

    def getSinaPriceInfo(self,code):
        url = "http://qt.gtimg.cn/q=" + code
        response = requests.get(url)
        content = response.text
        aStockInfo = content.split("~")
        return aStockInfo

    def getStockHyInfo(self,code):
        code = code.replace(".", "")
        fetch_http = FetchHttp()
        contents = fetch_http.fetch("http://quote.eastmoney.com/" + code + ".html")
        links = re.findall('<a.*?boardlist.html.*?<\/a>', contents)
        if links:
            dr = re.compile(r'<[^>]+>', re.S)
            hy = dr.sub('', links[0])
            return hy
        else:
            return ""

    def getHGTStock(self):
        fetch_http = FetchHttp()
        contents = fetch_http.fetch("http://www.sse.com.cn/services/hkexsc/disclo/eligible/")
        links = re.findall('\[.*?\n.*?\n.*?\n.*?\n.*?\]', contents)
        stock = {}
        for i in range(len(links)):
            codelist = re.findall('\"\d{5}\"',links[i])
            codenamelist = re.findall('\"[^\x00-\xff].*?\u3000\"', links[i])
            code = ''
            codename = ''
            for m in codelist:
                code = m.replace('\"',"")
            for e in codenamelist:
                codename = e.replace('\"',"")
                codename = codename.replace('\u3000','')
            stock[i] = [code,codename]
        return stock

    def add_market_code(self,code):
        codeall = code.split(".")
        x = codeall[1]
        y = '0.' + x
        if x.startswith('6'):
            y = '1.' + x
        return y

    def add_market_code(self,code):
        codeall = code.split(".")
        x = codeall[1]
        y = '0.' + x
        if x.startswith('6'):
            y = '1.' + x
        return y

    def translateDfcfCode(self,code):
        subfix = code[:1]
        if code == "sh000001":
            return "1.000001"
        if subfix == "6":
            code2 = "1." + code
        else:
            code2 = "0." + code

        return code2

    def translateSinaCode(self,code):
        subfix = code[:1]
        if subfix == "6":
            code2 = "sh" + code
        else:
            code2 = "sz" + code

        return code2

    def isZhuBan(self,code):
        isZhuban = True
        subfix = code[:3]
        subfix1 = code[:1]
        if subfix == "688" or subfix1 == "3":
            isZhuban = False
        return isZhuban

    '''
    f2：最新价，收盘价,f3：涨跌幅,f4：涨跌价,f5：成交量
    f6：成交额,f8：换手率,f9：市盈率（动）,f10：量比
    f12：代码,f14：名称,f15：最高价,f16：最低价
    f17：今开,f18：昨收价,f20：总市值,f21：流通市值,f23：市净率
    '''
    def getStockPriceByDFCF(self,code):
        #requests.adapters.DEFAULT_RETRIES = 5  # 增加重连次数
        #s = requests.session()
        #s.keep_alive = False  # 关闭多余连接
        endpoint = 'http://push2.eastmoney.com/api/qt/ulist.np/get'
        var1 = '?fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,f25,f26,f27,f28,f29,f30'
        var2 = '&invt=2&fltt=2&fid=f3'
        var3 = '&ut=bd1d9ddb04089700cf9c27f6f7426281&cb=&secids='
        url = '{0}{1}{2}{3}{4}'.format(endpoint, var1, var2, var3, code)
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,'
                      'application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
            'Connection': 'close',
            'Cookie': 'timezoneOffset=28800,0; _ga=GA1.2.2068924460.1568258364; browserid=1637567403399993326; '
                      'sessionid=0be65a169d686e464855602e; _gid=GA1.2.614169347.1590475272; '
                      'steamMachineAuth76561199007171441=CA87107A153BDC24FE6D54504A124395F9C36243; '
                      'deep_dive_carousel_focused_app=673750; deep_dive_carousel_method=gems; '
                      'steamCountry=HK%7C413cfd508f5a328ba1679f9252231a8e; '
                      'app_impressions=377530@1_7_7_topsellers_150_3|1245200@1_7_7_topsellers_150_3|632360'
                      '@1_7_7_topsellers_150_3|1245180@1_7_7_topsellers_150_3|1298590@1_7_7_topsellers_150_3|285900'
                      '@1_7_7_topsellers_150_3|632470@1_7_7_topsellers_150_2|813780@1_7_7_topsellers_150_2|1100600'
                      '@1_7_7_topsellers_150_2|1293820@1_7_7_topsellers_150_2|952860@1_7_7_topsellers_150_2|1209110'
                      '@1_7_7_topsellers_150_2|1015610@1_7_7_topsellers_150_3|1238440@1_7_7_topsellers_150_3|1042550'
                      '@1_7_7_topsellers_150_3|466560@1_7_7_topsellers_150_3|602960@1_7_7_topsellers_150_3|457140'
                      '@1_7_7_topsellers_150_3|793460@1_7_7_topsellers_150_3|512540@1_7_7_topsellers_150_3|619150'
                      '@1_7_7_topsellers_150_3|1100410@1_7_7_topsellers_150_3|1088780@1_7_7_topsellers_150_3|1100420'
                      '@1_7_7_topsellers_150_3|1201360@1_7_7_topsellers_150_3|642280@1_7_7_topsellers_150_3|673950'
                      '@1_7_7_topsellers_150_3|613830@1_7_7_topsellers_150_3|636480@1_7_7_topsellers_150_3|387990'
                      '@1_7_7_topsellers_150_3|414700@1_7_7_topsellers_150_3|382310@1_7_7_topsellers_150_3|1162520'
                      '@1_7_7_topsellers_150_2|289070@1_7_7_topsellers_150_2|307690@1_7_7_topsellers_150_2|973760'
                      '@1_7_7_topsellers_150_2|1273370@1_5_9__405; recentapps=%7B%22578080%22%3A1590476900%7D',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20210911 Firefox/52.0'
        }
        try:
            response = httpx.get(url, headers=headers, verify=False, timeout=5)
            #response = s.get(url, headers=headers,verify=False,timeout=5)
            data = response.json()
        except:
            return False

        response = requests.get(url)
        data = response.json()
        if data['rc'] == 102:
            return False
        else:
            return data['data']['diff']

    '''
    f189：上市日期
    '''
    def getDfcfInfo(self,code):
        url = "http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2" \
              "&fields=f319,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167," \
              "f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149," \
              "f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111," \
              "f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270," \
              "f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282," \
              "f189,f284,f285,f286,f287,f292&secid="+ self.translateDfcfCode(code) +"&_=1620525195200"
        response = requests.get(url,headers=self.headers)
        data = response.json()
        if data['rc'] == 102:
            return False
        else:
            return data['data']

    def getDfcfHyInfo(self,code):
        url = "http://push2.eastmoney.com/api/qt/slist/get?pn=1&pz=6&po=1" \
              "&fid=f3&spt=3&fields=f1%2Cf2%2Cf3%2Cf12%2Cf13%2Cf14%2Cf152&secid=" + self.translateDfcfCode(code) + "&invt=2&fltt=2&_=1620524222775"
        try:
            response = httpx.get(url, headers=self.headers, verify=False, timeout=5)
            # response = s.get(url, headers=headers,verify=False,timeout=5)
            data = response.json()
            if data['rc'] == 102:
                return False
            else:
                return data['data']['diff']
        except:
            return False

    def getDfcfLineDay(self,code,n=3):
        url = "http://88.push2his.eastmoney.com/api/qt/stock/kline/get?secid="+ self.translateDfcfCode(code) +"&ut=fa5fd1943c7b386f172d6893dbfba10b" \
              "&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61" \
              "&klt=101&fqt=0&end=20500101&lmt=" + str(n) + "&_=1620518200989"
        try:
            response = httpx.get(url, headers=self.headers, verify=False, timeout=5)
            # response = s.get(url, headers=headers,verify=False,timeout=5)
            data = response.json()
            if data['rc'] == 102:
                return False
            else:
                return data['data']
        except:
            return False

    def getDfcfMinite(self,code):
        url = "http://92.push2.eastmoney.com/api/qt/stock/trends2/sse?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f17" \
              "&fields2=f51,f52,f53,f54,f55,f56,f57,f58&mpi=1000" \
              "&secid="+ self.translateDfcfCode(code) +"&ndays=1"
        try:
            print(url)
            response = requests.get(url, headers=self.headers, verify=False, timeout=5)
            # response = s.get(url, headers=headers,verify=False,timeout=5)
            print(response)
            data = response.json()
            if data['rc'] == 102:
                return False
            else:
                return data['data']
        except:
            return False

    def getGaiNian(self,code):
        hystr = ""
        hyinfo = self.getDfcfHyInfo(code)
        if hyinfo != False:
            for i in hyinfo:
                hystr += hyinfo[i]["f14"] + ","
        return hystr

    def getParserOption(self,code):
        url = "http://data.eastmoney.com/stockcomment/api/" + code + ".json"
        response = requests.get(url)
        data = response.json()
        content = ''
        if "qsyp" in data["ApiResults"]:
            content += "【综合评价】" + "<br/>"
            gailv = data["ApiResults"]["zhpj"]["RiseAndFallPredict"][0]
            content += "次日上涨概率：" + gailv["NextDayRoseProbability"][:5] + "%，五日上涨概率：" + gailv["NextFiveDayRoseProbability"][:5]+ "%<br/>"
            content += "【资金】" + "<br/>"
            jszb = data["ApiResults"]["zj"]["Trend"][0][0]
            if "PressurePosition" in jszb and "SupportPosition" in jszb and "RChange60" in jszb and "TurnoverRate60" in jszb:
                ylw = "压力位:" + jszb["PressurePosition"] + "，支撑位:" + jszb["SupportPosition"]
                ylw += "，60日区间涨幅：" + jszb["RChange60"][:5] + "%，60日换手率：" + jszb["TurnoverRate60"][:5] +"%"
                content += ylw + "<br/>"
            content += "【资金动向】" + "<br/>"
            content += data["ApiResults"]["zjdx"]["Summary"][0]["Comment"] + "<br/>"
            content += "【价值评估】" + "<br/>"
            content += data["ApiResults"]["jzpg"]["ValueReview"][0]["Comment"] + "<br/>"
        return content

    def getDfcfHyMoney(self):
        url = ("https://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=500&po=1&np=1&"
               "fields=f12%2Cf13%2Cf14%2Cf62&fid=f62&fs=m%3A90%2Bt%3A2&ut=b2884a393a59ad64002292a3e90d46a5&_="+str(int(time.time()*1000)))
        try:
            print(url)
            response = requests.get(url, headers=self.headers, verify=False, timeout=5)
            # response = s.get(url, headers=headers,verify=False,timeout=5)
            data = response.json()
            if data['rc'] == 102:
                return False
            else:
                return data['data']["diff"]
        except:
            return False

    """
    获取指数信息
    """
    def getDfcfZsInfo(self):
        url = ("https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&secids=1.000001%2C0.399001&"
               "fields=f1%2Cf2%2Cf3%2Cf4%2Cf6%2Cf12%2Cf13%2Cf104%2Cf105%2Cf106&ut=b2884a393a59ad64002292a3e90d46a5&_="+str(int(time.time()*1000)))
        try:
            response = requests.get(url, headers=self.headers, verify=False, timeout=5)
            # response = s.get(url, headers=headers,verify=False,timeout=5)
            data = response.json()
            if data['rc'] == 102:
                return False
            else:
                return data['data']["diff"]
        except:
            return False

    """
    获取净流入
    """
    def getJingliuru(self,code):
        if str(code) != str("1.000001") and str(code) != str("0.399001"):
            code = self.translateDfcfCode(code)
        url = ("https://push2.eastmoney.com/api/qt/stock/fflow/kline/get?lmt=0&klt=1&fields1=f1%2Cf2%2Cf3%2Cf7"
               "&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65"
               "&ut=b2884a393a59ad64002292a3e90d46a5&secid=")+ str(code) +"&_=" + str(int(time.time() * 1000))
        try:
            response = requests.get(url)
            # response = s.get(url, headers=headers,verify=False,timeout=5)
            data = response.json()
            if data['rc'] == 102:
                return False
            else:
                return data["data"]
        except:
            return False